package com.scorekeeper;

import java.util.Map;

import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.scorekeeper.objects.Division;
import com.scorekeeper.objects.Team;
import com.scorekeeper.utils.HTTPLoad;
import com.scorekeeper.utils.Loader;
import com.scorekeeper.utils.Logger;

import android.app.Activity;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.widget.Toast;

public class RefreshStandings extends Fragment {
	public static Context ctx = null;
	
	private Activity parent = null;
	private ProgressDialog mProgressDialog = null;
	private String teamName;
	
	public static RefreshStandings newInstance() {
		RefreshStandings f = new RefreshStandings();
		Bundle args = new Bundle();
		
		f.setArguments(args);
		return f;
	}
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        parent =this.getActivity();
        ctx = parent.getApplicationContext();
        
        loadFromWeb();
    }
    
    public void loadFromWeb() {
    	try {
			new Thread(new Runnable() {
				public void run() {
					Document doc;
					
					doc = HTTPLoad.loadStandings();
					if (doc != null) {
						if (mProgressDialog.isShowing())
							parent.runOnUiThread(new Runnable() {
								public void run() {
									mProgressDialog.setMessage("Loading Division Data ... ");
								}
							});
						
						Map<Long, Division> divisions = HTTPLoad.buildDivisionData(doc);
						
						buildTeamData(doc, divisions);
						
						mProgressDialog.dismiss();
					} else {
						if (mProgressDialog.isShowing())
							parent.runOnUiThread(new Runnable() {
								public void run() {
									Toast.makeText(ctx, "Unable to load data, check WIFI and Proxy settings", Toast.LENGTH_LONG).show();
									if (mProgressDialog.isShowing())
										mProgressDialog.dismiss();
								}
							});
					}
				}
			}).start();
			
			mProgressDialog = ProgressDialog.show(parent, "Please wait...", "Downloading standings data ... ", true);
			
		} catch (Exception e) {
			Logger.LogError(e);
			mProgressDialog.dismiss();
		}
    }
    
    public void buildTeamData(Document doc, Map<Long, Division> divisions) {
    	int default_child_node = getResources().getInteger(R.integer.child_node_default);
    	int itemIdx;
    	
    	Team team = null;
		Element teamRows = doc.body().select("tbody").get(2);
		
		for (Element teamRow : teamRows.select("tr")) {
			Elements teamInfo = teamRow.getAllElements();
			//during playoff time, names are prefixed with 'x -', 'y -', or '* -' chars
			// denoting playoff race status they are stored in a new span elm
			itemIdx = 5;
			if (teamInfo.get(itemIdx).tagName() == "span")
				itemIdx = 6;
			
			teamName = teamInfo.get(itemIdx).childNode(default_child_node).toString();
			
			//search for the team
			team = new Loader().loadTeam(teamName);			
			if (team == null) 
				team = new Team();
			
			parent.runOnUiThread(new Runnable() {
				public void run() {
					mProgressDialog.setMessage("Building data for " + teamName + " ... ");
				}
			});
			
			team.name = teamName;
			team.acro = teamInfo.get(itemIdx).attr("rel").toString();
			
			String divAcro = teamInfo.get(++itemIdx).childNode(default_child_node).toString();
			team.gamesPlayed = Integer.parseInt(teamInfo.get(++itemIdx).childNode(default_child_node).toString());
			team.wins = Integer.parseInt(teamInfo.get(++itemIdx).childNode(default_child_node).toString());
			team.losses = Integer.parseInt(teamInfo.get(++itemIdx).childNode(default_child_node).toString());
			team.points = Integer.parseInt(teamInfo.get(itemIdx += 2).childNode(default_child_node).toString());
			
			for (Division div : divisions.values()) {
				if (div.acro.equalsIgnoreCase(divAcro)) {
					team.divisionId = div._id;
					break;
				}
			}
			team.save();
			
			team.loadExtensions();
			HTTPLoad.buildTeamExtensionData(teamInfo, team._id, team.extensions, itemIdx);
		}
    }
}